﻿package com.shangda.Server;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Timer;

import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;

import com.shangda.entity.ReceiveData;
import com.shangda.frame.MainFrame;
import com.shangda.frame.TimeOclock;
import com.shangda.service.DataService;
import com.shangda.util.RequestHandel;

public class EchoServer implements Runnable {
	
	//数据库保存类
	private DataService dataService;
    //要监听的端口号
    private int port;
    //生成一个信号监视器
    private Selector s;
    //读缓冲区
    private ByteBuffer temp = ByteBuffer.allocate(1024);
    
    //维护时间已经跟新的sewageId;
    private List<Integer> timeChanges;
    
    //主截面对象
    private MainFrame mainFrame;
    
    //维护当前所有活动站点编号
    private List<String> sewageIds;
    //时间对象
    private TimeOclock o;
    
    public EchoServer() throws IOException {
    	try {
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
			BeautyEyeLNFHelper.launchBeautyEyeLNF();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	mainFrame = new MainFrame();
    	mainFrame.init();
    	//初始化socketChannel
    	sewageIds = new ArrayList<String>();
    	
    	o = new TimeOclock(mainFrame);
    	Timer t = new Timer();
    	t.schedule(o,1,5000);
    	
    	
    	//获取配置文件的port
    	FileInputStream in = new FileInputStream("properties/config.properties");
    	Properties p = new Properties();
    	p.load(in);
    	String serverPort = p.getProperty("port");
    	mainFrame.getServerPortField().setText(serverPort);
    	this.port = Integer.parseInt(serverPort);
    	
        this.dataService = new DataService();
        this.timeChanges = new ArrayList<Integer>();
        try {
            s = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        new Thread(this).start();
    }
 
    @Override
    public void run() {
        try {
            //生成一个ServerScoket通道的实例对象，用于侦听可能发生的IO事件
            ServerSocketChannel ssc = ServerSocketChannel.open();
            //将该通道设置为异步方式
            ssc.configureBlocking(false);
            //绑定到一个指定的端口
            ssc.socket().bind(new InetSocketAddress(port));
            //注册特定类型的事件到信号监视器上
            ssc.register(s, SelectionKey.OP_ACCEPT);
            while(true) {
                //将会阻塞执行，直到有事件发生
                s.select();
                Iterator<SelectionKey> it = s.selectedKeys().iterator();
                while(it.hasNext()) {
                    SelectionKey key = it.next();
                    //key定义了四种不同形式的操作
                    
                    if (key.isAcceptable()){
                    	dealwithAccept(key);
                    }else if (key.isReadable()){
                    	try {
							dealwithRead(key);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
                    }
                    //处理结束后移除当前事件，以免重复处理
                    it.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    
    //处理接收连接的事件
    private void dealwithAccept(SelectionKey key) {
    	SocketChannel sc = null;
    	try {
            ServerSocketChannel server = (ServerSocketChannel)key.channel();
            sc = server.accept();
            sc.configureBlocking(false);
            //注册读事件
            sc.register(s, SelectionKey.OP_READ);
            //给客户端发送连接信息   老系统不需要 
            sc.write(ByteBuffer.wrap(new byte[] {35,1}));
            
			} catch (Exception e) {
				e.printStackTrace();
			}  
    }
    
    
    
    //处理客户端发来的消息，处理读事件
    private void dealwithRead(SelectionKey key) throws Exception  {
    	
    	//这是一个read事件，并且这个事件是建立在socketChannel上的
		SocketChannel sc = (SocketChannel) key.channel();
		
		//写数据到buffer
		temp.clear();
		int count = 0;
		try {
			count = sc.read(temp);
			
		} catch (Exception e) {
			//sc.close();
			//key.cancel();
			e.printStackTrace();
			return ;
		}
		if (count < 0){
			//客户端断开连接
			//sc.close();
			//key.cancel();
			return;
		}
		//切换buffer到读状态,内部指针归为
		temp.flip();
		
		//将bytebuffer转成shows
		byte[] shows = temp.array();
		
		//处理数据逻辑  8991逻辑  江都的接收程序
		ReceiveData receiveData = null;
		if (port == 8991){
			try {
				//receiveData = RequestHandel.dataHandelJD(shows, count, sc, dataService, timeChanges);
			} catch (Exception e) {
				if (e instanceof IOException){
					//sc.close();
					//key.cancel();
					e.printStackTrace();
					return;
				}
			}
		}
		
		//老系统的接收程序
		if (port == 8990){
			
			//receiveData = RequestHandel.dataHandelOrigin(shows, count, dataService);
			
			
		}
		
		
		
		//显示发送端信息
		mainFrame.getSendIpField().setText(sc.socket().getInetAddress().toString().substring(1));
		mainFrame.getSendPortField().setText(sc.socket().getPort()+"");
		if (receiveData != null){
			mainFrame.getDatas().setText(receiveData.toString());
			mainFrame.getSewageIdField().setText(receiveData.getSewageId() +"");
			
			//加入sewageID
			if (!sewageIds.contains(receiveData.getSewageId()+"")){
				sewageIds.add(receiveData.getSewageId()+"");
				//显示连接总数
				mainFrame.getTotalConnectionField().setText(sewageIds.size()+"");
				
				mainFrame.getActivitySewage().addItem(receiveData.getSewageId()+"");
				
			}
			
		}
	
		
		
		
		Thread.sleep(1000);
		temp.clear();
       
    }
    
    public static void main(String[] args) {
    	try {
			new EchoServer();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    
    
}

